package org.sgx.joptest.server.rpc;

import java.util.Date;

import org.sgx.dao.BeanDao;
import org.sgx.dao.ConnectionGiver;
import org.sgx.dao.Dao;
import org.sgx.dao.test.test1.testModel.BeanTest1;
import org.sgx.joptest.client.model.User;
import org.sgx.joptest.client.rpc.GreetingService;
import org.sgx.joptest.server.PersistenceManager;
import org.sgx.joptest.server.ServerUtil;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UserServiceImpl extends RemoteServiceServlet implements GreetingService {


	@Override
	public Long addUser(User u) {
		try {
			ConnectionGiver con = PersistenceManager.getValidConnectionGiver(); 
			Dao<User> dao1 = new BeanDao<User>(con, User.class);
			
			//first we drop the table and then recreate the table in database for having a clean table to work with
			dao1.dropTable(); 
			dao1.createTable();
			
//			Date date1 = new Date();
//			User bean1 = new User("hello", 888l, true, date1);		
//			assertTrue(dao1.listAll().size()==0);
			
			//add
			long newId = dao1.add(u);
//			BeanTest1 bean1_ = dao1.get(newId);
//			assertTrue(bean1.equals(bean1_));		
//			assertEquals(bean1, bean1_);
//			assertTrue(dao1.listAll().size()==1);
			return newId;
		} catch (Exception e) {
			ServerUtil.dispatchError(e);
			return -1l;
		}
	}
	
	
	public String greetServer(String input) throws IllegalArgumentException {

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>"
				+ userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
	}

}
